package com.sskj.gateway.controller;

import com.sskj.common.dto.EncodedCommand;
import com.sskj.common.util.ApiResponseUtil;
import com.sskj.common.vo.ApiResponse;
import com.sskj.common.vo.req.DeviceCommandReq;
import com.sskj.gateway.service.IDeviceCommandService;
import com.sskj.gateway.session.DeviceSession;
import com.sskj.gateway.session.DeviceSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/gateway/internal")
public class InternalCommandController {

    @Autowired
    private DeviceSessionManager sessionManager;

    @Autowired
    private Map<String, IDeviceCommandService> commandServiceMap;

    @PostMapping("/command")
    public ApiResponse<Object> sendCommand(@RequestBody DeviceCommandReq request) {
        String deviceCode = request.getDeviceCode();
        DeviceSession session = sessionManager.getSession(deviceCode);

        if (session == null) {
            return ApiResponseUtil.fail("设备未注册");
        }

        // 根据协议类型编码并下发
        IDeviceCommandService deviceCommandService = commandServiceMap.get(session.getProtocol().toLowerCase());
        if (deviceCommandService == null) {
            return ApiResponseUtil.fail("未配置" + session.getProtocol() + "命令下发策略");
        }
        try {
            EncodedCommand command = deviceCommandService.send(request);
            return ApiResponseUtil.success(command.getMetadata());
        } catch (RuntimeException e) {
            log.error("[下发指令失败。失败信息:{}]", e.getMessage());
            return ApiResponseUtil.fail(e.getMessage());
        }
    }
}
